package pfq.demo.okhttp;

import android.os.Bundle;
import android.util.Log;
import android.view.View;

import java.io.IOException;

import androidx.appcompat.app.AppCompatActivity;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import pfq.demo.R;

public class OkHttpActivity extends AppCompatActivity implements View.OnClickListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ok_http);

        findViewById(R.id.activity_ok_http_syn_btn).setOnClickListener(this);
        findViewById(R.id.activity_ok_http_asyn_btn).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.activity_ok_http_syn_btn:

                sendSynRequest();

                break;
            case R.id.activity_ok_http_asyn_btn:
                break;
        }
    }

    /**
     * 发起一个同步请求
     */
    private void sendSynRequest() {
        new Thread() {
            @Override
            public void run() {
                super.run();
                try {

                    // 创建一个客户端
                    OkHttpClient okHttpClient = new OkHttpClient().newBuilder().addInterceptor(new SwitchURLInterceptor()).addNetworkInterceptor(new TestNetworkInterceptor()).build();

                    // 创建一个请求
                    Request request = new Request.Builder().url("https://wanandroid.com/wxarticle/list/408/1/json").build();

                    // 创建一个RealCall，发起请求，此处的execute()方法表示执行一个同步请求
                    Response response = okHttpClient.newCall(request).execute();
                    if (response.isSuccessful()) {
                        Log.d("pangfq", "返回成功：" + response.body().string());
                    } else {
                        Log.d("pangfq", "返回错误: " + response.code());
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();


    }
}
